import {
  NavigationGuardNext,
  RouteLocationNormalized
} from 'vue-router'
import router, { addRoutes } from './router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
// import { useStore } from "vuex"
import store from '@/store'
import { UserActionTypes } from './store/modules/user'
import { permissionActionTypes } from './store/modules/permission'
import { ElLoading, ElMessage } from 'element-plus'
import { ILoadingInstance } from 'element-plus/lib/el-loading/src/loading.type'

// 白名单
const WhiteList = ['/login']

router.beforeEach(
  async (
    to: RouteLocationNormalized,
    from: RouteLocationNormalized,
    next: NavigationGuardNext
  ) => {
    NProgress.start()
    const { roles, token } = store.getters
    // 如果存在token，表示已登录
    if (token) {
      if (!roles) {
        let loadingInstance: ILoadingInstance | null = ElLoading.service({ fullscreen: true, text: '路由跳转中' })
        try {
          const { roles } = await store.dispatch(
            UserActionTypes.ACTION_GET_USER_INFO
          )
          const routes = await store.dispatch(
            permissionActionTypes.ACTION_SET_ROUTES,
            roles
          )

          // 添加动态路由
          addRoutes(routes)

          next({ ...to, replace: true })
        } catch (error) {
          console.log(error)
          ElMessage.error('获取用户信息失败，即将跳转到登录页')
          store.dispatch(UserActionTypes.ACTION_LOGIN_OUT)
          next(`/login?redirect=${to.path}`)
        }
        loadingInstance.close()
        loadingInstance = null
        return
      }
      if (to.path === '/login') {
        next({ path: '/home' })
        return
      }
      next()
      return
    }

    // 处理未登录的情况
    // 如果是不需要登录的名单，则直接过去
    if (WhiteList.includes(to.path)) {
      next()
      return
    }
    // 否则则重定向回登录页
    next(`/login?redirect=${to.path}`)
  }
)

router.afterEach(() => {
  NProgress.done()
})
